package dhm.com.hpx.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.AllImageAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.entity.Result;
import dhm.com.hpx.entity.ResultDetailCallback;
import dhm.com.hpx.utils.BitmapUtil;
import dhm.com.hpx.utils.SpUtils;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

public class DynamicActivity extends BaseActivity {

    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.recy)
    RecyclerView recy;
    private AllImageAdapter adapter;
    private ArrayList<Bitmap> image = new ArrayList<>();
    private static final int REQUEST_IMAGE = 2;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    private ArrayList<String> mSelectPath;
    private String uid;


    @Override
    protected int getLayout() {
        return R.layout.activity_dynamic;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        uid = SpUtils.getString(this, "uid");

        GridLayoutManager manager=new GridLayoutManager(this,3);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        adapter = new AllImageAdapter(this);
        recy.setAdapter(adapter);
        adapter.setaddClick(new AllImageAdapter.OnIntentClick() {
            @Override
            public void item() {
                pickImage();
            }
        });

        adapter.setdeleteClick(new AllImageAdapter.OnClick() {
            @Override
            public void item(int posttion) {
                mSelectPath.remove(posttion);
                image.remove(posttion);
                adapter.showImage(image);
            }
        });


    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.back, R.id.add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.add:
                String contents = content.getText().toString();
                if (contents==null||contents.equals("")){
                    Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                PostFormBuilder postFormBuilder = OkHttpUtils.post().url(Constant.PATH + Constant.dynamic_add)
                        .addParams("token", Constant.TOKEN)
                        .addParams("uid", uid)
                        .addParams("dynamic_con", contents);
                Map<String, File> files = new HashMap<>();

                try {
                    for (int i = 0; i < image.size(); i++) {
                        files.put(bitmapToString(image.get(i)), new File(bitmapToString(image.get(i))));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                postFormBuilder.files("image[]", files)
                        .build().execute(new ResultDetailCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DynamicActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result response, int id) {
                        Toast.makeText(DynamicActivity.this, response.getMessage(), Toast.LENGTH_LONG).show();
                        if (response != null && response.getCode() == 1) {
                            finish();
                        }
                    }
                });
                break;
                default:
        }
    }
    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            int maxNum = 6;
            MultiImageSelector selector = MultiImageSelector.create(DynamicActivity.this);
            selector.showCamera(true);
            selector.count(maxNum);
            selector.multi();
            selector.origin(mSelectPath);
            selector.start(DynamicActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(DynamicActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                image.clear();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                    Bitmap bitmap = BitmapUtil.getScaleBitmap(p, 0, 0);
                    image.add(bitmap);
                }
                adapter.showImage(image);
            }
        }
    }
    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }


}
